import React, {useEffect} from "react";
import {Alert, Pressable, View} from "react-native";
import * as ScreenOrientation from "expo-screen-orientation";
import * as MediaLibrary from "expo-media-library";
import ImageViewer from "react-native-image-zoom-viewer";
import Ionicons from "@expo/vector-icons/Ionicons";
import styles from "./image-preview.style";
import {useRoute} from "@react-navigation/native";
import {OrientationLock} from "expo-screen-orientation";
import {router} from "expo-router";
import SystemUtils from "@/utils/system-utils";
import {useChatMessageState} from "@/hooks/chat/chat-message";

interface ImagePreviewerRouteProps {
    uri: string;
}

export default function ImagePreviewer() {
    const route = useRoute();
    const {uri} = route.params as ImagePreviewerRouteProps;
    const {imgUrls} = useChatMessageState();
    const currentIndex = imgUrls.findIndex((img) => img.url === uri);

    const [permissionResponse, requestPermission] = MediaLibrary.usePermissions({
        writeOnly: true,
    });

    const savePicture = async () => {
        try {
            const {status} = await MediaLibrary.requestPermissionsAsync();
            if (status === "granted") {
                await MediaLibrary.saveToLibraryAsync(uri);
                SystemUtils.showSystemAlert("文件已保存到相册");
            } else {
                SystemUtils.showSystemAlert("请允许应用访问相册权限以保存文件");
            }
        } catch (e) {
            Alert.alert("保存失败");
        }
    };
    const saveImage = async () => {
        if (!permissionResponse.granted) {
            const resp = await requestPermission();
            if (resp.granted) {
                await savePicture();
            }
        }
        await savePicture();
    };

    useEffect(() => {
        // 解锁屏幕方向，允许旋转
        ScreenOrientation.unlockAsync();
        // 监听屏幕方向变化
        const listenOrientation = () => {
            return ScreenOrientation.addOrientationChangeListener((event) => {
                console.log(event);
            });
        };
        const listener = listenOrientation();
        return () => {
            ScreenOrientation.removeOrientationChangeListener(listener); // 移除屏幕方向变化监听
            ScreenOrientation.lockAsync(OrientationLock.DEFAULT); // 锁定屏幕方向
        };
    }, []);

    return (
        <View style={{flex: 1, backgroundColor: "black"}}>
            <ImageViewer
                imageUrls={imgUrls}
                index={currentIndex}
                enableSwipeDown
                renderIndicator={() => null}
                saveToLocalByLongPress={false}
            />
            <Pressable style={styles.closeBtn} onPress={() => router.back()}>
                <Ionicons name="close" size={28} color="white"/>
            </Pressable>
            <Pressable style={styles.saveBtn} onPress={saveImage}>
                <Ionicons name="download-outline" size={28} color="white"/>
            </Pressable>
        </View>
    );
}
